<?php
namespace backend\modules\admin\controllers;

use Yii;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\modules\admin\models\Role;
use backend\modules\admin\models\Admin;
use yii\data\ActiveDataProvider;
use yii\web\Response;
use common\models\User;
use yii\helpers\Url;
use common\models\District;
use common\models\Department;
use common\models\Branch;
use backend\components\Chat;

/**
 * Admin controller
 */
class AdminController extends Controller
{
    public function actions()
    {
        return [
            'upload' => [
                'class' => 'common\action\UploadAction',                    //独立动作url
                'config' => [
                    "is_html"=>true,                                        //是否静态化
                    "re_type"=>'normal'                                  //返回格式 可选项：'swfupload','normal'
                ],
            ],
        ];
    }

    /**
     * 管理员列表
     * @return string
     */
    public function actionIndex(){
        //对管理员进行分页处理
        $dataProvider = new ActiveDataProvider([
            'query' => Admin::find()->where(['status'=>'0'])->orderBy(''),
            'pagination' => [
                'pageSize' => ADMINPAGENUM,
            ],
            'sort' => [
                'defaultOrder' => [
                    'userid' => SORT_ASC,

                ]
            ],
        ]);       
        $roles = new Role();//实例化role
        //跳转到列表页
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'roles'=>$roles,
        ]);

    }
    //管理员添加
    public function actionAddadmin()
    {
        $model = new Admin();
        $roles = Role::find()->where(['status'=>'0'])->all();//获取role表中所有可以显示的数据
        $rs = [
            'url'=>'index',//跳转页面，若为goback,则返回上一页
            'msg'=>'添加失败',//跳转自定义信息
            'ms'=>5000,//延迟时间
            'msg_type'=>'error'//消息类型，success,error,close
        ];
        $username = Admin::find()->select('username')->where(['status'=>0])->asArray()->all();
        if($model->load(Yii::$app->request->post()))//获取表单提交过来的数据并保存到数据库中
        {
            if($model->validate())
            {
                $chat = new Chat();
                $url = 'https://a1.easemob.com/1165180419146683/jnwmpaidan/users';
                $data = array(
                    'username'=>$model->username,
                    'password'=>'123456',
                    'nickname'=>$model->realname,
                );

                $return = $chat->vpost($url,$data);
                if(isset($return->entities))
                {
                    foreach($username as $key=>$val)
                    {
                        $f_url = 'https://a1.easemob.com/1165180419146683/jnwmpaidan/users/'.$model->username.'/contacts/users/'.$val['username'];
                        $f_return = $chat->vpost($f_url);
                    }
                    $model->save();
                    return $this->render('//msg',
                    [
                        'url'=>'',//跳转页面，若为goback,则返回上一页
                        'msg'=>'添加成功',//跳转自定义信息
                        'ms'=>5000,//延迟时间
                        'msg_type'=>'success'//消息类型，success,error,close
                    ]);
                }
                else
                {
                    return $this->render('//msg',
                    [
                        'url'=>'index',//跳转页面，若为goback,则返回上一页
                        'msg'=>'添加失败，'.$return->error_description,//跳转自定义信息
                        'ms'=>5000,//延迟时间
                        'msg_type'=>'error'//消息类型，success,error,close
                    ]);
                }
                
                
            }
            else
            {
                return $this->render('//msg',$rs);
            }
        }
        else
        {
            //$model_district = new District();
            //$district = $model_district->find()->select('dt_id,dt_name')->where(['parentid'=>1])->asArray()->all();
            $model_department = new Department();
            $department = $model_department->find()->select('dp_id,dp_name')->all();
            return $this->render('addadmin', [
                'model' => $model,
                'roles'=>$roles,
                'district'=>$district,
                'department'=>$department
            ]);
        }
    }
    //管理员更新
    public function actionUpdateadmin($userid,$roleid)
    {
        //在admin表中查询到传过来的userid的这一条信息
        $model = Admin::findOne([
            'userid' => $userid,
        ]);
        $rol = Role::find()->where(['status'=>'0','roleid'=>$roleid])->one();//在role表中查询到传过来的roleid的这一条信息
        $roles = Role::find()->where(['status'=>'0'])->all();//获取role表中所有可以显示的数据
        $rs = [
            'url'=>'index',//跳转页面，若为goback,则返回上一页
            'msg'=>'修改失败',//跳转自定义信息
            'ms'=>5000,//延迟时间
            'msg_type'=>'error'//消息类型，success,error,close
        ];
        if($model->load(Yii::$app->request->post()))//获取表单提交过来的数据并保存到数据库中
        {
            if($model->validate())
            {
                $model->save(); 
                return $this->render('//msg',
                [
                    'url'=>'',//跳转页面，若为goback,则返回上一页
                    'msg'=>'修改成功',//跳转自定义信息
                    'ms'=>1000,//延迟时间
                    'msg_type'=>'success'//消息类型，success,error,close
                ]);
            }
            else
            {
                return $this->render('//msg',$rs);
            }
        }
        else
        {
            
            $model_department = new Department();
            $department = $model_department->find()->select('dp_id,dp_name')->all();
            return $this->render('updateadmin',[
                'model' => $model,
                'roles'=>$roles,
                'rol'=>$rol,
               
                'department'=>$department
            ]);
        }
    } 
    //成员更新
    public function actionUpdatemember($userid,$roleid)
    {
        $model = Admin::findOne([ //在admin表中查询到传过来的userid的这一条信息
            'userid' => $userid,
        ]);
        $rol = Role::find()->where(['status'=>'0','roleid'=>$roleid])->one();
        $roles = Role::find()->where(['status'=>'0'])->all();
        //Yii::app()->request->urlReferrer
        $rs = [
            'url'=>'/admin/role/rolemember?roleid='.$roleid,//跳转页面，若为goback,则返回上一页
            'msg'=>'修改失败',//跳转自定义信息
            'ms'=>5000,//延迟时间
            'msg_type'=>'error'//消息类型，success,error,close
        ];
        if($model->load(Yii::$app->request->post()) && $model->save())
        {
            if($model->validate())
            {
                $model->save(); 
                return $this->render('//msg',
                [
                    'url'=>'/admin/role/rolemember?roleid='.$roleid,//跳转页面，若为goback,则返回上一页
                    'msg'=>'修改成功',//跳转自定义信息
                    'ms'=>1000,//延迟时间
                    'msg_type'=>'success'//消息类型，success,error,close
                ]);
            }
            else
            {
                return $this->render('//msg',$rs);
            }
            //return $this->redirect(['role/rolemember','roleid'=>$roleid]);//保存成功跳转到roleid的角色管理的成员列表页
        }
        else
        {
            return $this->render('updateadmin',[
                'model' => $model,
                'roles'=>$roles,                
                'rol'=>$rol,                
            ]);
        }
    }
    //管理员删除
    public function actionDeleteadmin($userid)
    {
        Yii::$app->response->format=Response::FORMAT_JSON;//因为响应格式为HTML, 只需要在操作方法中返回一个字符串。
        $admin = Admin::findOne([
            'userid' => $userid,
        ]);
        //当管理员的角色为超级管理员时，不能删除
        if($admin->roleid==1)
        {
            return ['msg'=>'此管理员不可删除','status'=>0]; 
        }
        $admin->status = '-1';//软删除
        $res=$admin->save();//保存到数据库中
        //当执行删除操作后的提示信息
        if($res)
        {
            return ['msg'=>'删除成功','status'=>-1];
        }
        else
        {
            return ['msg'=>'删除失败','status'=>0];
        }
    }

    /**
     * 前台支部管理员信息
     * @param int $branch_id 支部编号
     * @return string
     */
    public function actionManager($branch_id=0)
    {
        $where['isAdmin'] = 1;
        if($branch_id){
            $where['branch_id'] = $branch_id;
        }
        //对管理员进行分页处理
        $model_user = new User();
        $dataProvider = new ActiveDataProvider([
            'query' => $model_user->find()->where($where)->orderBy('id DESC'),
            'pagination' => [
                'pageSize' => ADMINPAGENUM,
            ],
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,

                ]
            ],
        ]);
        //跳转到列表页
        return $this->render('manager', [
            'dataProvider' => $dataProvider,
            'model_user'=>$model_user
        ]);
    }

    /**
     * 添加支部管理员
     * @return string
     */
    public function actionAddmanager($branch_id = 0)
    {
        $model = new User();
        $post=Yii::$app->request->post('User');

        if( $post && !empty($post['id']))
        {
            $rs = $model->updateAll(['isAdmin' => 1], [ 'in', 'id', $post ]);
            return $this->render('//msg',
                [
                    'url'=>Url::toRoute('/admin/admin/manager'),//跳转页面，若为goback,则返回上一页
                    'msg'=>'添加成功',//跳转自定义信息
                    'ms'=>1000,//延迟时间
                    'msg_type'=>'success'//消息类型，success,error,close
                ]);
        }

        $model_branch = new Branch();
        $branchs = $model_branch->getMenu('',"<option value='\$id' \$selected >\$spacer\$name</option>");

        return $this->render('addM',
            [
                'branchs'=>$branchs
            ]);
    }

    public function actionDelmanager()
    {
        if($id = Yii::$app->request->get('id'))
        {
            $model = User::findOne($id);
            $model->isAdmin = 0;
            $rs = $model->save();
            return $this->render('//msg',
                [
                    'url'=>Url::toRoute('manager'),//跳转页面，若为goback,则返回上一页
                    'msg'=>'已取消管理权限',//跳转自定义信息
                    'ms'=>1000,//延迟时间
                    'msg_type'=>'success'//消息类型，success,error,close
                ]);
        }
        return $this->render('//msg',
            [
                'url'=>'',//跳转页面，若为goback,则返回上一页
                'msg'=>'请先指定支部管理员',//跳转自定义信息
                'ms'=>1000,//延迟时间
                'msg_type'=>'success'//消息类型，success,error,close
            ]);
    }

    //测试环信昵称获取
    public function actionGetnickname()
    {
        Yii::$app->response->format=Response::FORMAT_JSON;//因为响应格式为HTML, 只需要在操作方法中返回一个字符串。
        if($_GET['name'])
        {
            $name = $_GET['name'];
            $nickname = Yii::$app->session['nickname'];
            return $nickname[$name];
        }
        else
        {
            return '';
        }
        
    }
}
